package cn.iocoder.yudao.boot.web.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.boot.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.boot.web.filter.CacheRequestBodyWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * API 访问日志 Interceptor
 */
@Slf4j
public class AccessLogInterceptor implements HandlerInterceptor {

    public static final String ATTRIBUTE_HANDLER_METHOD = "HANDLER_METHOD";

    private static final String ATTRIBUTE_STOP_WATCH = "ApiAccessLogInterceptor.StopWatch";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 记录 HandlerMethod，提供给 ApiAccessLogFilter 使用
        HandlerMethod handlerMethod = handler instanceof HandlerMethod ? (HandlerMethod) handler : null;
        if (handlerMethod != null) {
            request.setAttribute(ATTRIBUTE_HANDLER_METHOD, handlerMethod);
        }

        // 打印 request 日志
        if (request instanceof CacheRequestBodyWrapper) {
            log.info("可以打印body入参");
            Map<String, String> queryString = ServletUtils.getParamMap(request);
            String requestBody = ServletUtils.isJsonRequest(request) ? ServletUtils.getBody(request) : null;
            if (CollUtil.isEmpty(queryString) && StrUtil.isEmpty(requestBody)) {
                log.info("[开始请求 {}:{} 无参数]", request.getMethod(), request.getRequestURI());
            } else {
                log.info("[开始请求 {}:{} 参数({})]", request.getMethod(), request.getRequestURI(), StrUtil.blankToDefault(requestBody, queryString.toString()));
            }
        } else {
            Map<String, String> queryString = ServletUtils.getParamMap(request);
            if (CollUtil.isEmpty(queryString)) {
                log.info("[开始请求 {}:{} 无参数]", request.getMethod(), request.getRequestURI());
            } else {
                log.info("[开始请求 {}:{} 参数({})]", request.getMethod(), request.getRequestURI(), queryString.toString());
            }
        }
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        request.setAttribute(ATTRIBUTE_STOP_WATCH, stopWatch);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 打印 response 日志
        StopWatch stopWatch = (StopWatch) request.getAttribute(ATTRIBUTE_STOP_WATCH);
        stopWatch.stop();
        log.info("[完成请求 {}:{} 耗时({} ms)]", request.getMethod(), request.getRequestURI(), stopWatch.getTotalTimeMillis());
    }

}
